#!/usr/bin/perl -w

use strict;
use lib '/usr/local/apache/lib';
use DeDBI;
use DE;
use DeImage;
use DeUtils qw(is_primary_server);
use POSIX ();
use URI::Escape;
use Data::Dumper;
use Getopt::Long;
use File::Basename;
use ServerConfiguration;
use Data::Dumper;

BEGIN {
    $ENV{ORACLE_HOME}   = '/usr/local/oracle';
    $ENV{TWO_TASK}      = 'newdb';
}

print "\n primary server: " . PRIMARYSERVER . " server: " . SERVER . " \n ";
exit 0 unless is_primary_server();

my %opts;
GetOptions(
    "template=s"    => \$opts{template},
    "engine=s"      => \$opts{engine},
    "debug=s"       => \$opts{debug},
    "dryrun=s"      => \$opts{dryrun},
);

#die $0;

die %opts unless ($opts{template} && $opts{engine});
die 'engine is not allowed' unless (grep { $opts{engine} eq $_ } qw/
am nff caf bf
sdm sum jpl cnc kfd
lc df vfs
eqc tf spd
stdmm
gk lf
irm
sc nmm
bc
bk
milf mf
gm
ms mt
/);

=comment
Deafs 8,
bicupid 31, SugardaddyMeet 2054, MilitaryFriends 32768, CougarMingle 2055, TallFriends 28,
MuslimFriends 4096 and SingleParentmatch 15.
=cut



my $engine = $opts{engine};


$DE::TextTemplate::MAILTPLDIR = dirname($0);

my $sql = q{
    select fname, email
    from af_user
    where engine = ?
        and email is not null
        and (nvl(block_cb_url, 0) = 0 and active != 5)
};

my $sql_test = q{
    select fname, email
    from af_user
    where upper(email) in ('CHARLIEZHANG66@GMAIL.COM', 'BEATRICEXIE@GMAIL.COM', 'SAMSHENG133@GMAIL.COM')
        and engine = ?
};

$sql = $sql_test if ($opts{debug});

my $dbh = DeDBI->connect();

my ($engine_id, $engine_title) = $dbh->selectrow_array(q{
select id, descr
from de_params
where short_name = ?
    and upper(server) = ?
}, {}, $engine, SERVER);


my $rec = $dbh->selectall_arrayref($sql, {}, $engine_id);
foreach my $record (@$rec) {
    my ($fname, $email) = @$record;
    my %SendmailARGS;

    $SendmailARGS{template} = $opts{template};
    $SendmailARGS{engine} = $engine;
    $SendmailARGS{engine_name} = $engine_title;
    $SendmailARGS{fname} = $fname;
    $SendmailARGS{email} = $email;

    if ($opts{dryrun}) {
        print Dumper(\%SendmailARGS);
    } else {
        DE::sendEmail(\%SendmailARGS);
    }
    sleep(2);
}